using UnityEngine;
using System.Net;
using System.Collections;
using System.Collections.Generic;

public class GameMenus : MonoBehaviour
{
    public string playerName;

    public delegate void GUIMenu();
    public GUIMenu currentMenu;

    private float lastHostListRequest = -1000f;
    private float hostListRefreshTimeout = 10f;

    //Game list field
    public float tableWidth = 476;
    public float tableHeight = 200;
    public float gameNameWidth = 150;
    public float nbPlayersWidth = 60;
    public float commentWidth = 150;
    public float joinButtonWidth = 70;
    public float lineHeigth = 20;
    public float cellSpace = 5;
    public float lineSpace = 2;
    public Vector2 scrollGames;

    //Windows fields
    private bool showHostWindow = false;
    private bool showIpWindow = false;
	private bool showOnlineHostWindow = false;
	private bool showOnlineSearchWindow = false;
    private Rect windowPopUp;

    private string gameName = "New Game";
    private string serverIp = "127.0.0.1";
    private string serverPort = "25001";
    private string nbPlayers = "2";
    private string maxKills = "15";
	

    public void Awake()
    {
        if (playerName == "")
        {
            playerName = PlayerPrefs.GetString("playerName");
        }
        currentMenu = HostJoin;
    }

    public void DrawGUI()
    {
        //TODO : Replace by a background image
        GUILayout.Label("Project Byblus");
        currentMenu();
    }
    public void HostJoin()
    {
		//Quit
		//
		GUILayout.BeginArea(new Rect(Screen.width / 2 - 175, Screen.height / 2 - 100, 350, 200));

        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        GUILayout.Label("Enter your name :");
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        playerName = GUILayout.TextField(playerName, GUILayout.MaxWidth(120), GUILayout.MinWidth(120));
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Quit", GUILayout.MaxWidth(60)))
        {
            Application.Quit();
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
		//
		//
        windowPopUp = new Rect(Screen.width / 2 - 125, Screen.height / 2 - 175, 250, 350);

        if (showIpWindow)
        {
            windowPopUp = GUI.Window(0, windowPopUp, JoinByIP, "Join a local Game by IP");
        }

        if (showHostWindow)
        {
            windowPopUp = GUI.Window(0, windowPopUp, HostGame, "Host a local Game");
        }
		
		if (showOnlineHostWindow)
        {
            windowPopUp = GUI.Window(0, windowPopUp, OnlineHostGame, "Host a online Game");
        }
		if (showOnlineSearchWindow)
		{
			windowPopUp = GUI.Window(0, windowPopUp, OnlineSearchGame, "Search online game");
		}
		
		//Game List
        float xTopLeft = (Screen.width - tableWidth) / 2;
		
		//Local Game
        GUILayout.BeginArea(new Rect(xTopLeft, ((Screen.height - tableHeight) / 3 + tableHeight + 45), tableWidth, 60));
        GUILayout.BeginArea(new Rect(0, 0, tableWidth, 30));
		GUILayout.BeginHorizontal();
		GUILayout.Label("Local Game");
		GUILayout.EndHorizontal();
		GUILayout.EndArea();
		GUILayout.BeginArea(new Rect(0, 30, tableWidth, 30));
		GUILayout.BeginHorizontal();
        GUI.enabled = !(showHostWindow || showIpWindow || showOnlineHostWindow);
        if (GUILayout.Button("Enter an IP"))
        {
            showIpWindow = true; //display the popup window
			this.GetComponent<GeneralManager>().playerName = playerName;
        }
        if (GUILayout.Button("Host a local Game"))
        {
            showHostWindow = true; //display the popup window
			this.GetComponent<GeneralManager>().playerName = playerName;
        }
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
		GUILayout.EndArea();
		//Online Game
		GUILayout.BeginArea(new Rect(xTopLeft, ((Screen.height - tableHeight) / 3 + tableHeight + 105), tableWidth, 60));
        GUILayout.BeginArea(new Rect(0, 0, tableWidth, 30));
		GUILayout.BeginHorizontal();
		GUILayout.Label("Online Game");
		GUILayout.EndHorizontal();
		GUILayout.EndArea();
		GUILayout.BeginArea(new Rect(0, 30, tableWidth, 30));
		GUILayout.BeginHorizontal();
        GUI.enabled = !(showHostWindow || showIpWindow || showOnlineHostWindow);
        if (GUILayout.Button("Search a Online Game"))
        {
            //display the popup window
			this.GetComponent<Networking>().RefreshMasterServerList();
			showOnlineSearchWindow = true; //display the popup window
			this.GetComponent<GeneralManager>().playerName = playerName;
        }
		if (GUILayout.Button("Host a Online Game"))
        {
  	        showOnlineHostWindow = true; //display the popup window
			this.GetComponent<GeneralManager>().playerName = playerName;
        }
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
		GUILayout.EndArea();
    }
	
	public void InitializeChat(){
		 PlayerPrefs.SetString("playerName", playerName);
            this.GetComponent<GeneralManager>().playerName = playerName;
            this.GetComponent<Chat>().pseudo = playerName;
            //currentMenu = GamesListMenu;
	}
    /// <summary>
    /// Open a GUI Window to connect by server ip
    /// </summary>
    public void JoinByIP(int windowID)
    {
        GUILayout.Label("Server IP :");
        serverIp = GUILayout.TextField(serverIp, GUILayout.MinWidth(100));
        GUILayout.Label("Server port :");
        serverPort = GUILayout.TextField(serverPort);

        if (GUILayout.Button("Connect"))
        {
            int port = int.Parse(serverPort);
            showIpWindow = false;
            this.GetComponent<Networking>().DirectConnectToServer(serverIp, port);
			InitializeChat();
        }
        if (GUILayout.Button("Back"))
        {
            showIpWindow = false;
        }
    }

    /// <summary>
    /// Open a GUI Windows to configure a host game
    /// </summary>
    public void HostGame(int windowID)
    {
        GUILayout.Label("Game Name :");
        gameName = GUILayout.TextField(gameName, GUILayout.MinWidth(50));
        GUILayout.Label("Server port :");
        serverPort = GUILayout.TextField(serverPort);
		
		
		if (GUILayout.Button("Start"))
        {
            //initialise server/game manager
            int port = int.Parse(serverPort);
            showHostWindow = false;
            this.GetComponent<Networking>().StartServer(gameName, port);
			InitializeChat();
        }
        GUI.enabled = true;

        if (GUILayout.Button("Back"))
        {
            showHostWindow = false;
        }
    }
	
	/// <summary>
    /// Open a GUI Windows to configure a online host game
    /// </summary>
    public void OnlineHostGame(int windowID)
    {
        GUILayout.Label("Game Name :");
        gameName = GUILayout.TextField(gameName, GUILayout.MinWidth(50));
		
		if (GUILayout.Button("Start"))
        {
            //initialise server/game manager
            int port = int.Parse(serverPort);
            showOnlineHostWindow = false;
			// Use NAT punchthrough if no public IP present
            this.GetComponent<Networking>().StartOnlineServer(gameName, 25002);
			InitializeChat();
        }
        GUI.enabled = true;

        if (GUILayout.Button("Back"))
        {
            showOnlineHostWindow = false;
        }
    }
	
	/// <summary>
    /// Open a GUI Windows to list all servers availables
    /// </summary>
    public void OnlineSearchGame(int windowID)
    {
		int i = 0;
		HostData[] hostData = this.GetComponent<Networking>().hostData;
        while (i < hostData.Length) 
		{
			if (GUILayout.Button("GAME : " + hostData[i].gameName))
	        {
	            int port = int.Parse(serverPort);
	            showOnlineSearchWindow = false;
				Debug.Log(hostData[i].ip[0] );
	            this.GetComponent<Networking>().DirectConnectToOnlineServer(hostData[i].ip, hostData[i].port);
				InitializeChat();
	        }
            i++;
        }
        if (GUILayout.Button("Back"))
        {
            showOnlineSearchWindow = false;
        }
    }
	
	

    /// <summary>
    /// This is the looby
    /// </summary>
    public void ChatRoom()
    {
		Rect rect = new Rect(10, (Screen.height * 0.45f), 300, (Screen.height * 0.5f));
        this.GetComponent<Chat>().DrawChat(rect);
        //Connected Players List
        GUI.Box(new Rect((Screen.width * 0.75f) + 25, 50, (Screen.width * 0.25f) - 50, Screen.height * 0.5f), "Players");
        GUILayout.BeginArea(new Rect((Screen.width * 0.75f) + 25, 50, (Screen.width * 0.25f) - 25, (Screen.height * 0.5f) - 50));
        GUILayout.Space(15);
        GUILayout.BeginVertical();
        foreach (KeyValuePair<string, NetworkPlayer> player in this.GetComponent<Networking>().playersByName)
        {
			GUILayout.BeginHorizontal();
			Color color = new Color();
			if ( this.GetComponent<Networking>().readyPlayers.ContainsKey(player.Value))
			{
				if ( this.GetComponent<Networking>().readyPlayers[player.Value] )
				{
					color = Color.cyan;
				}
				else
				{
					color = Color.white;
				}
				GUI.color = color;
	            GUILayout.Label(player.Key);
				if ( this.GetComponent<Networking>().readyPlayers.ContainsKey(Network.player) && player.Value == Network.player )
				{
					if ( ! this.GetComponent<Networking>().readyPlayers[Network.player] && this.GetComponent<Networking>().readyPlayers.Count == 2 )
					{
						if (GUILayout.Button("Ready", GUILayout.MaxWidth(60)))
				        {
							this.GetComponent<Networking>().NewPlayerReady();
				        }
					}
				}
						GUI.color = Color.white;
					}
			GUILayout.EndHorizontal();
		  }
        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
	
	/// <summary>
    /// This is the game menu
    /// </summary>
    public void Game()
    {
		Rect rect = new Rect(10, (Screen.height * 0.45f), 300, (Screen.height * 0.5f));
        this.GetComponent<Chat>().DrawChat(rect);
        //Connected Players List
        GUI.Box(new Rect((Screen.width * 0.0f), (Screen.height * 0.1f), (Screen.width * 0.1f), (Screen.height * 0.1f)), "game menu");
    }
	
	public void OnPlayersReady()
    {
		 currentMenu = Game;
    }


    public void OnServerInitialized()
    {
        this.GetComponent<Chat>().SetWindowChat(25, 50, (Screen.width * 0.75f) - 25, (Screen.height * 0.5f) - 41);
        currentMenu = ChatRoom;
    }

    public void OnConnectedToServer()
    {
        this.GetComponent<Chat>().SetWindowChat(25, 50, (Screen.width * 0.75f) - 25, (Screen.height * 0.5f) - 41);
        currentMenu = ChatRoom;
    }

    public void OnDisconnectedFromServer(NetworkDisconnection info)
    {
        currentMenu = HostJoin;
    }

    public void OnFailedToConnect(NetworkConnectionError error)
    {
        currentMenu = HostJoin;
    }

    public void OnFailedToConnectToMasterServer(NetworkConnectionError error)
    {
        currentMenu = HostJoin;
    }
	public void InfoNeutralChat(string msg)
	{
		if ( Network.isServer && !this.GetComponent<GeneralManager>().isDebugFightingScene) // seulement l'host qui envoi les infos
		{
			this.GetComponent<Chat>().AddAnnonce(msg, "", "yellow");	
		}
	}
}
